<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg"><i class="iconfont icon-dibudaohanglan-"></i> 地铁线路</div>
      <div class="item-wrapper">
        <div class="item" v-for="(item, index) in subLineData" :key="index" @click.stop="handleItemClick(item)">
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 站点列表 -->
    <div id="station-controller">
      <div class="title-bg"><i class="iconfont icon-ditiezhan"></i> 地铁站点</div>
      <div class="item-wrapper">
        <div class="item" :key="index" v-for="(item, index) in stationData">
          <div
            class="box"
            :style="{
              backgroundColor: index - 1 < metroIndex ? '#fff' : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useLineData } from '@/store';
import SimpleLabel from '@/cesiumTools/Bubble/htmlMarker';
import { getPositions, getSiteTimes } from '@/cesiumTools/core';

let viewer;
const subLineData = ref([]);
const stationData = ref([]);
const lineData = useLineData();
const currentLine = ref({});
let popupController;
let trainEntity;
const metroIndex = ref(0);

// 渲染轨道列车
const renderTrain = trainInfo => {
  // 获取出发站点，得到metroIndex
  const { startIndex, currentPosition, currentSpeed } = trainInfo;
  metroIndex.value = startIndex;
  // 获取当前位置在路径中的索引
  const pathIndex = currentLine.value.paths.findIndex(path => path === currentPosition);
  // 处理漫游效果
  const { property, startTime, endTime } = handlePosition(currentSpeed, pathIndex);
  trainEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: startTime,
        stop: endTime,
      }),
    ]),
    position: property,
    orientation: new Cesium.VelocityOrientationProperty(property),
    model: {
      scale: 0.17,
      uri: '/src/assets/model/metro.gltf',
      minimumPixelSize: 40, // 最小像素大小
    },
  });

  viewer.trackedEntity = trainEntity; // 使相机跟踪列车
  viewer.clock.startTime = startTime.clone();
  viewer.clock.stopTime = endTime.clone();
  viewer.clock.currentTime = startTime.clone();
  // 监听时钟，如果列车到达站点，更新列车人数信息，并给一个暂停时间
  //onTick事件会在每次时钟更新时触发
  viewer.clock.onTick.addEventListener(tickEventHandler);
  //这个要先设置为true，否则时间不会动
  viewer.clock.shouldAnimate = true;
};

// 清除所有副作用
const removeCurrentRoute = () => {
  // 释放视角,trainEntity当前相机正在跟踪的实体实例
  viewer.trackedEntity = null;
  trainEntity && viewer.entities.remove(trainEntity);
  // 移除气泡框
  popupController && popupController.removeMarker();
  tickEventHandler && viewer.clock.onTick.removeEventListener(tickEventHandler);
  // 重置时钟
  viewer.clock.shouldAnimate = false;
};

// 处理漫游效果，使用TimeIntervalCollection
const handlePosition = (speed, pathIndex) => {
  const property = new Cesium.SampledProperty(Cesium.Cartesian3);
  // 这里的时间可以自己定义
  let startTime = Cesium.JulianDate.fromDate(new Date(2015, 1, 1, 8));
  //通过速度计算最终时间
  const restPath = currentLine.value.paths.slice(pathIndex, currentLine.value.paths.length - 1);
  //转为Caterian3数组
  const positions = getPositions(restPath);
  //根据速度计算总时间和每段时间
  const { siteTimes, timeSum } = getSiteTimes(positions, speed);
  const endTime = Cesium.JulianDate.addSeconds(startTime, timeSum, new Cesium.JulianDate());
  positions.forEach((position, index) => {
    const time = Cesium.JulianDate.addSeconds(startTime, siteTimes[index], new Cesium.JulianDate());
    property.addSample(time, position);
  });
  return {
    property,
    startTime,
    endTime,
  };
};

// 渲染气泡框
const renderBubble = trainInfo => {
  const { currentPosition, currentPassengers, lineName } = trainInfo;
  const position = new Cesium.Cartesian3.fromDegrees(currentPosition.lng, currentPosition.lat);
  //创建气泡框
  popupController = new SimpleLabel(viewer, {
    position,
    label: null,
    isShow: true,
    color: '#fff',
    scaleByDistance: null,
    offset: [130, 200],
    attr: {
      currentPassengers,
      lineName,
    },
    type: 'carPopup',
  });
  popupController.addLabel();
};

// 当距离小于20米的时候，就可以给列车一个暂停
let apporachDistance = 20;
const tickEventHandler = () => {
  const startPosition = trainEntity.position.getValue(viewer.clock.currentTime);
  //通过当前的metroIndex和速度计算下一个站点的坐标
  const { position } = stationData.value[metroIndex.value + 1];
  const endPosition = new Cesium.Cartesian3.fromDegrees(position.lng, position.lat);
  let distance = Cesium.Cartesian3.distance(startPosition, endPosition);
  if (distance <= apporachDistance) {
    // 站点id变大，下一次计算的distance也会变大
    metroIndex.value++;
    // 将列车暂停
    viewer.clock.shouldAnimate = false;
    // 2s后恢复
    setTimeout(() => {
      viewer.clock.shouldAnimate = true;
    }, 2000);
  }
  // 还需要通过startPosition计算气泡框坐标
  popupController && popupController.changePosition(startPosition);
};

// 模拟从服务端获取到列车的实时信息
const getTrainDataByLineId = id => {
  return new Promise((resolve, reject) => {
    // 当前列车的起始站索引
    let startIndex = 0;
    // 当前列车的起始站信息
    const startStationInfo = stationData.value[startIndex];
    // 当前列车的终点站信息
    const endStationInfo = stationData.value[startIndex + 1];
    // 模拟列车数据
    const trainData = {
      startIndex, // 起始站索引
      currentPassengers: Math.ceil(Math.random() * 1000), // 当前乘客数
      startStation: startStationInfo, // 起始站信息
      destination: endStationInfo, // 终点站信息
      lineName: currentLine.value.name, // 线路名称
      currentSpeed: Math.ceil(Math.random() * 500), // 当前速度
      currentPosition: currentLine.value.paths[0], // 当前位置
    };
    resolve(trainData);
  });
};

const handleItemClick = async item => {
  // 如果点击的是同一个站线，返回
  if (currentLine.value?.name == item.name) return;
  // 释放视角，删除列车
  removeCurrentRoute();
  // 更新当前线路
  currentLine.value = item;
  // 点击站线，更新数据，渲染轨道列车，视角跳转，渲染popup
  const { stationsList, id } = item;
  // 控制ui
  subLineData.value.forEach(item => {
    if (item.id == id) {
      item.choosed = true;
    } else {
      item.choosed = false;
    }
  });
  stationData.value = stationsList;
  // 从模拟服务端获取列车信息
  const trainInfo = await getTrainDataByLineId(id);
  // 渲染轨道列车
  renderTrain(trainInfo);
  // 渲染气泡框
  renderBubble(trainInfo);
};

onMounted(() => {
  subLineData.value = lineData.allData.map(item => ({
    ...item,
    choosed: false,
  }));
  // console.log(subLineData.value);
  // console.log(subLineData.value);
  viewer = lineData.Viewer;
});

onBeforeUnmount(() => {
  // 清除所有副作用
  removeCurrentRoute();
});
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 90px;
  left: 32.5%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
  z-index: 100;
  user-select: none; /* 阻止文本选中 */
  -webkit-user-select: none; /* 兼容 Safari */
  -moz-user-select: none; /* 兼容 Firefox */
  -ms-user-select: none; /* 兼容 IE/Edge */
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 600px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 38%;
  bottom: 90px;
  color: #fff;
  display: flex;
  flex-direction: column;
  z-index: 100;
  user-select: none; /* 阻止文本选中 */
  -webkit-user-select: none; /* 兼容 Safari */
  -moz-user-select: none; /* 兼容 Firefox */
  -ms-user-select: none; /* 兼容 IE/Edge */
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>
